<?php
namespace app\hotback\controller;
use think\Db;
use app\service\TechnService;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
class Technapply extends Base
{
	public function _initialize()
	{
		// 调用父类前置方法
		parent::_initialize();

		// 登录校验
		$this->IsLogin();
	}

	public function index()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			if(!empty($params['page']) && !empty($params['limit']))
			{
				$map = [
					'is_delete_time' => 0
				];
				if(!empty($params['real_name']))
				{
					$map['real_name'] = ['like','%'.$params['real_name'].'%'];
				}

                if(!empty($params['mobile']))
                {
                    $map['mobile'] = $params['mobile'];
                }

                if(!empty($params['type']))
                {
                    $map['type'] = $params['type'];
                }
                if(!empty($params['proxy_id']))
                {
                    $is_xian = Db::name('proxy')->where('proxy_id',$params['proxy_id'])->find();
                    if ($is_xian['is_xian'] == 0){
                        $not = Db::name('proxy')->where('shi',$is_xian['shi'])->where('proxy_id','<>',$is_xian['proxy_id'])->column('qu');
                        $map['city'] = $is_xian['shi'];
                        if (!empty($not)){
                            $map['qu'] = ['not in',implode(',',$not)];
                        }
                    }else{
                        $map['county'] = $is_xian['qu'];
                    }
                }
				if(!empty($params['status'])){
				    if($params['status']=='-1'){
				        $params['status']=0;
				    }
				    $map['status']=$params['status'];
				}
				
				$count = Db::name('techn_apply')->where($map)->count();
				$list_data = Db::name('techn_apply')->where($map)->order('id desc')->limit(($params['page']-1)*$params['limit'],$params['limit'])->select();
				if(!empty($list_data))
				{
					//申请类型
					$type_apply_array = TechnService::$type_apply_array;
					//性别
					$sex_array = TechnService::$sex_array;
					//审核最终状态
					$status_over_apply_array = TechnService::$status_over_apply_array;
					//遍历处理
					foreach($list_data as $key => $value)
					{
						//查询用户
						$user_info = Db::name('user')->where(['id' => $value['user_id']])->find();
						$list_data[$key]['user_info'] = !empty($user_info) ? $user_info : [];

						//性别
						$list_data[$key]['sex_name'] = !empty($sex_array[$value['sex']]['name']) ? $sex_array[$value['sex']]['name'] : '';
						//类型
						$list_data[$key]['type_name'] = !empty($type_apply_array[$value['type']]['name']) ? $type_apply_array[$value['type']]['name'] : '';
						//最终状态
						$list_data[$key]['status_name'] = !empty($status_over_apply_array[$value['status']]['name']) ? $status_over_apply_array[$value['status']]['name'] : '';
						//获取当前步骤的审核状态
						$list_data[$key]['no_step_status'] = Db::name('techn_audit')->where(['techn_apply_id' => $value['id'], 'no_step' => $value['no_step']])->value('status');

						//详情url
						$list_data[$key]['detail_url'] = url('Technapply/detail', ['id' => $value['id']]);
					}
					$result['code'] = 0;
	        		$result['msg'] = "请求成功";
	        		$result['data'] = $list_data;
	        		$result['count'] = $count;
				}else
				{
					$result['code'] = -1;
	        		$result['msg'] = "暂无数据";
				}
			}
			echo json_encode($result);
		}else
		{
            $proxy = Db::name('proxy')->where('is_delete_time',0)->select();
            $this->assign('proxy',$proxy);
			return $this->fetch();
		}
	}

	/**
	 * 通过审核
	 */
	public function audit()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			//查询审核信息
			$techn_apply_info = Db::name('techn_apply')->where(['id' => intval($params['id']), 'is_delete_time' => 0])->find();
			if(empty($techn_apply_info))
			{
				echo json_encode(['code' => -1, 'msg' => '审核内容不存在']);
				exit();
			}
			if(!in_array($techn_apply_info['status'], [0, 1]))
			{
				echo json_encode(['code' => -1, 'msg' => '审核状态不可操作']);
				exit();
			}
			//查询附表信息
			$techn_audit_info = Db::name('techn_audit')->where(['techn_apply_id' => $techn_apply_info['id'], 'no_step' => $techn_apply_info['no_step'], 'status' => 0])->find();
			if(empty($techn_audit_info))
			{
				echo json_encode(['code' => -1, 'msg' => '审核内容不存在']);
				exit();
			}
			
			//查询技师是否存在
			$techn_info = Db::name('techn')->where(['user_id' => $techn_apply_info['user_id']])->find();
			//判断审核类型
			switch ($techn_apply_info['type']) {
				//入驻申请
				case 1:
					if(!empty($techn_info))
					{
						echo json_encode(['code' => -1, 'msg' => '技师已存在']);
						exit();
					}
				break;
				//资料修改申请
				case 2:
				    if(empty($techn_info))
				    {
				    	echo json_encode(['code' => -1, 'msg' => '技师不存在']);
						exit();
				    }
				break;
			}
			//事务操作
			//启动事务
			Db::startTrans();
			try{
				//更新申请主表
				Db::name('techn_apply')->where(['id' => $techn_apply_info['id']])->update([
					'audit_step' => Db::raw('audit_step+1'),
					'status' => ($techn_apply_info['audit_step']+1) >= $techn_apply_info['steps'] ? 2 : 1,
					'upd_time' => time()
				]);
				//更新申请附表
				Db::name('techn_audit')->where(['id' => $techn_audit_info['id']])->update([
					'status' => 1,
					'audit_time' => time(),
					'upd_time' => time()
				]);
				if(($techn_apply_info['audit_step']+1) >= $techn_apply_info['steps'])
				{
					//审核完成写入技师表
					//判断审核类型
					switch ($techn_apply_info['type']) {
						//入驻申请
						case 1:
						    $techn_id = Db::name('techn')->insertGetId([
						    	'user_id' => $techn_apply_info['user_id'],
						    	'real_name' => $techn_apply_info['real_name'],
						    	'sex' => $techn_apply_info['sex'],
						    	'age' => $techn_apply_info['age'],
						    	'work_year' => $techn_apply_info['work_year'],
						    	'mobile' => $techn_apply_info['mobile'],
						    	'province' => $techn_apply_info['province'],
						    	'city' => $techn_apply_info['city'],
						    	'county' => $techn_apply_info['county'],
						    	'province_name' => $techn_apply_info['province_name'],
						    	'city_name' => $techn_apply_info['city_name'],
						    	'county_name' => $techn_apply_info['county_name'],
						    	'self_img' => $techn_apply_info['self_img'],
						    	'nickname' => $techn_apply_info['nickname'],
						    	'address' => $techn_apply_info['address'],
						    	'lng' => $techn_apply_info['lng'],
						    	'lat' => $techn_apply_info['lat'],
						    	'service_ids' => $techn_apply_info['service_ids'],
						    	'descs' => $techn_apply_info['descs'],
						    	'id_card_img' => $techn_apply_info['id_card_img'],
						    	'diploma_img' => $techn_apply_info['diploma_img'],
						    	'work_img' => $techn_apply_info['work_img'],
						    	'sos_phone' => $techn_apply_info['sos_phone'],
						    	'video' => $techn_apply_info['video'],
						    	'add_time' => time(),
						    	'upd_time' => time()
						    ]);
						    //写入技师实时数据
						    Db::name('techn_last')->insertGetId([
						    	'techn_id' => $techn_id,
						    	'province' => $techn_apply_info['province'],
						    	'city' => $techn_apply_info['city'],
						    	'county' => $techn_apply_info['county'],
						    	'province_name' => $techn_apply_info['province_name'],
						    	'city_name' => $techn_apply_info['city_name'],
						    	'county_name' => $techn_apply_info['county_name'],
						    	'address' => $techn_apply_info['address'],
						    	'lng' => $techn_apply_info['lng'],
						    	'lat' => $techn_apply_info['lat'],
						    	'add_time' => time(),
						    	'upd_time' => time()
						    ]);
						break;
						//资料修改申请
						case 2:
						    $techn_data = [
						    	//'user_id' => $techn_apply_info['user_id'],
						    	'real_name' => $techn_apply_info['real_name'],
						    	'sex' => $techn_apply_info['sex'],
						    	'age' => $techn_apply_info['age'],
						    	'work_year' => $techn_apply_info['work_year'],
						    	'mobile' => $techn_apply_info['mobile'],
						    	'province' => $techn_apply_info['province'],
						    	'city' => $techn_apply_info['city'],
						    	'county' => $techn_apply_info['county'],
						    	'province_name' => $techn_apply_info['province_name'],
						    	'city_name' => $techn_apply_info['city_name'],
						    	'county_name' => $techn_apply_info['county_name'],
						    	'self_img' => $techn_apply_info['self_img'],
						    	'nickname' => $techn_apply_info['nickname'],
						    	'address' => $techn_apply_info['address'],
						    	'lng' => $techn_apply_info['lng'],
						    	'lat' => $techn_apply_info['lat'],
						    	'service_ids' => $techn_apply_info['service_ids'],
						    	'descs' => $techn_apply_info['descs'],
						    	'id_card_img' => $techn_apply_info['id_card_img'],
						    	'diploma_img' => $techn_apply_info['diploma_img'],
                                'sos_phone' => $techn_apply_info['sos_phone'],
						    	'work_img' => $techn_apply_info['work_img'],
						    	'video' => $techn_apply_info['video'],
						    	//'add_time' => time(),
						    	'upd_time' => time()
						    ];
						    Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_data);
						break;
					}
				}
				//提交事务
				Db::commit();
				$result['code'] = 0;
				$result['msg'] = "操作成功";
				//查询技师申请关联的用户openid
				$openid = Db::name('user_weixin')->where(['user_id' => $techn_apply_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
				if(!empty($openid) && $techn_apply_info['audit_step'] == 0 && $techn_apply_info['type'] == 1)
				{
					$tem_msg['touser'] = $openid;
					$tem_msg['template_id'] = 'SH78HDqJl2C4A7leKR43kcbKR_v5w46OdVwh5E_kG9M';
					$tem_msg['miniprogram'] = [
			        	'appid' => TechnWeixinService::$mini_appid,
			        	'pagepath' => 'pages/my/my'
			        ];
			        $tem_msg['data'] = [
			        	'first' => [
			                'value' => '初审已通过',
			                'color' => '#173177'
			            ],
			            'keyword1' => [
			                'value' => date('m月d日 H:i', $techn_apply_info['add_time']),
			                'color' => '#173177'
			            ],
			            'keyword2' => [
			                'value' => '初步审核',
			                'color' => '#173177'
			            ],
			            'remark' => [
			                'value' => '点击完善资料进行最终审核。',
			                'color' => '#173177'
			            ]
			        ];
			        UserWeixinService::send_wx_web_tem_msg($tem_msg);
				}
			} catch (\Exception $e) {
				//回滚事务
				Db::rollback();
				$result['code'] = -1;
				$result['msg'] = "操作失败";
			}
		}
		echo json_encode($result);
	}

	/**
	 * 删除审核信息
	 */
	public function delete()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			$data = [
				'is_delete_time' => time(),
				'upd_time' => time()
			];
			if(Db::name('techn_apply')->where(['id' => intval($params['id'])])->update($data))
			{
				$result['code'] = 0;
				$result['msg'] = "删除成功";
			}else
			{
				$result['code'] = -1;
				$result['msg'] = "删除失败";
			}
		}
		echo json_encode($result);
	}

	/**
	 * 申请详情
	 */
	public function detail()
	{
		// 参数
		$params = input();
		if(!empty($params['id']))
		{
			//查询
			$info = Db::name('techn_apply')->where(['id' => $params['id']])->find();
			if(!empty($info))
			{
				//性别
				$sex_array = TechnService::$sex_array;
				$info['sex_name'] = !empty($sex_array[$info['sex']]['name']) ? $sex_array[$info['sex']]['name'] : '';
				//处理技师服务项目
				$service_ids_array = !empty($info['service_ids']) ? explode(",", trim($info['service_ids'], ",")) : [];
				$info['service_list'] = Db::name('service')->where(['id' => ['in', $service_ids_array]])->select();
				
				$this->assign('info',$info);
				return $this->fetch();
			}
		}
		return "信息不存在";
	}
}